package com.pengshun.modules.security;

import com.alibaba.fastjson.JSON;
import com.pengshun.modules.common.BaseResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 2019/1/14.
 */

@Component
public class AjaxAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        BaseResult result= new BaseResult(1);
        if (e.getMessage().equals("Bad credentials")) {
            result.setErrors("用户名密码错误!");
        } else if (e.getMessage().equals("User is disabled")) {
            result.setErrors("用户已被封停!");
        } else {
            result.setErrors(e.getMessage());
        }
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.getWriter().write(JSON.toJSONString(result));
    }
}
